<template>
    <el-form label-width="110px" size="small" class="form-content">
        <el-row class="form-row">
            <el-col :span="12">
                <el-form-item label="产品代码:" v-if="isBatchStock">
                    <RiskEntryInput @set-entry-data="getEntryslist" :returnDatas="instruction.fundCode" />
                </el-form-item>
                <el-form-item label="组合编码:" v-if="isBatchStock" @change="handleChange(instruction.fundAccountCode, 'fundAccountCode')">
                    <el-select v-model="instruction.fundAccountCode" size="mini">
                        <el-option
                            v-for="i in computedFundAccountCodeSelectData"
                            :key="i.fundAccountCode"
                            :label="i.fundAccountCode + ' ' + i.fundAccountName"
                            :value="i.fundAccountCode"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="证券代码:" v-if="isBatchFund">
                    <el-select
                        ref="stockSelect"
                        v-model="instruction.stockCode"
                        @change="handleChange(instruction.stockCode, 'stockCode')"
                        filterable
                        clearable
                        @clearable="handleStockClear"
                        :filter-method="getstockCodeList"
                        :loading="selectLoading"
                        @visible-change="handleStockVisibleChange"
                        size="mini"
                    >
                        <el-option
                            v-for="i in stockCodeSelectData"
                            :key="i.stockCode"
                            :label="i.stockCode + ' ' + i.stockNameSt"
                            :value="i.stockCode"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="业务类型:">
                    <el-select v-model="instruction.businClass" size="mini">
                        <el-option value="I" label="上交所固定收益平台"> </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="委托方向:">
                    <el-select
                        v-model="instruction.orderDirection"
                        size="mini"
                        :class="['font-color-' + textColor]"
                        @change="handleChange(instruction.orderDirection, 'orderDirection')"
                    >
                        <el-option
                            v-for="i in orderDirectionSelectData"
                            :key="i.dictKey"
                            :label="i.dictKey + ' ' + i.dictKeyName"
                            :value="i.dictKey"
                            :style="handleOptionColor(i.dictKey)"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="到期收益率:">
                    <RiskInputNumber
                        :input="instruction.yield"
                        :field="'yield'"
                        :inputAfter="'%'"
                        :colorStyle="textColor"
                        :precision="2"
                        :maxlength="2"
                        @getInputNumber="getInputNumber(arguments)"
                    >
                    </RiskInputNumber>
                </el-form-item>
                <div v-if="isBatchFund">
                    <el-form-item label="净价价格:">
                        <RiskInputNumber
                            :input="instruction.orderPrice"
                            :inputAfter="'元'"
                            :colorStyle="textColor"
                            :precision="2"
                            :maxlength="15"
                            :field="'orderPrice'"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item label="全价价格:">
                        <RiskInputNumber
                            :input="fullPrice"
                            :inputAfter="'元'"
                            :colorStyle="textColor"
                            :precision="2"
                            :maxlength="15"
                            :field="'fullPrice'"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                </div>
                <el-form-item label="交易对手:" v-if="isBatchStock">
                    <el-select
                        v-model="instruction.opponentCode"
                        @change="handleChange(instruction.opponentCode, 'opponentCode')"
                        filterable
                        clearable
                        :filter-method="getOpponentCode"
                        :loading="selectLoading"
                        @visible-change="handleOpponentVisibleChange"
                        size="mini"
                    >
                        <el-option v-for="i in opponentCodeSelectData" :key="i.dictKey" :label="i.dictKey + ' ' + i.dictKeyName" :value="i.dictKey">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <div v-if="isBatchStock">
                    <el-form-item label="净价价格:">
                        <RiskInputNumber
                            :input="instruction.orderPrice"
                            :inputAfter="'元'"
                            :colorStyle="textColor"
                            :precision="2"
                            :maxlength="15"
                            :field="'orderPrice'"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item label="全价价格:">
                        <RiskInputNumber
                            :input="fullPrice"
                            :inputAfter="'元'"
                            :colorStyle="textColor"
                            :precision="2"
                            :maxlength="15"
                            :field="'fullPrice'"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                </div>
                <el-form-item label="指令数量:">
                    <RiskInputNumber
                        :input="instruction.orderAmount"
                        :inputAfter="'张'"
                        :colorStyle="textColor"
                        :maxlength="15"
                        :precision="2"
                        :field="'orderAmount'"
                        @getInputNumber="getInputNumber(arguments)"
                    >
                    </RiskInputNumber>
                </el-form-item>
                <el-form-item label="净价金额:">
                    <el-tooltip
                        v-if="instruction.orderBalance && instruction.orderBalance != ''"
                        placement="top"
                        :content="computedorderBalanceChinese"
                        :enterable="false"
                    >
                        <RiskInputNumber
                            :disabled="true"
                            :input="instruction.orderBalance"
                            :inputAfter="'元'"
                            :colorStyle="textColor"
                            :field="'orderBalance'"
                            :precision="2"
                            :maxlength="15"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-tooltip>
                    <RiskInputNumber
                        v-else
                        :disabled="true"
                        :input="instruction.orderBalance"
                        :field="'orderBalance'"
                        :inputAfter="'元'"
                        :colorStyle="textColor"
                        :precision="2"
                        :maxlength="15"
                        @getInputNumber="getInputNumber(arguments)"
                    >
                    </RiskInputNumber>
                </el-form-item>
                <el-form-item label="总应计利息:">
                    <RiskInputNumber
                        :disabled="true"
                        :input="totalInterest"
                        :inputAfter="'元'"
                        :colorStyle="textColor"
                        :precision="2"
                        :maxlength="15"
                        :field="'totalInterest'"
                        @getInputNumber="getInputNumber(arguments)"
                    >
                    </RiskInputNumber>
                </el-form-item>
                <el-form-item label="全价金额:">
                    <RiskInputNumber
                        :disabled="true"
                        :input="fullBalance"
                        :inputAfter="'元'"
                        :colorStyle="textColor"
                        :precision="2"
                        :maxlength="15"
                        :field="'fullBalance'"
                        @getInputNumber="getInputNumber(arguments)"
                    >
                    </RiskInputNumber>
                </el-form-item>
                <el-form-item label="交易对手:" v-if="isBatchFund">
                    <el-select
                        v-model="instruction.opponentCode"
                        @change="handleChange(instruction.opponentCode, 'opponentCode')"
                        filterable
                        clearable
                        :filter-method="getOpponentCode"
                        :loading="selectLoading"
                        @visible-change="handleOpponentVisibleChange"
                        size="mini"
                    >
                        <el-option v-for="i in opponentCodeSelectData" :key="i.dictKey" :label="i.dictKey + ' ' + i.dictKeyName" :value="i.dictKey">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>
    </el-form>
</template>
<script lang="ts">
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import RiskInputNumber from '@/pages/risk-measure/components/risk-input-number.vue';
import { getBusinessType } from '@/pages/risk-time/api';
import { SGU_CACHE } from '@/utils/diction-const-util';
import { handleTextColor, highlightColor, NumberToWords } from '@/utils/tools';
import { getUser } from '@/utils/user-util';
import { Vue, Component, Watch, Prop } from 'vue-property-decorator';

@Component({
    name: 'ShFixedForm',
    components: {
        RiskEntryInput,
        RiskInputNumber,
    },
})
// 上交所固收
export default class ShFixedForm extends Vue {
    @Prop()
    isBatchFund: boolean; // 多基金指令
    @Prop()
    isBatchStock: boolean; // 多证券指令
    @Prop()
    selectStockInfo: any;
    @Prop()
    detail: any;
    handleOptionColor = handleTextColor;

    textColor: string = ''; // 红绿凸显

    // 风控指令表单
    instruction: any = {
        businClass: 'I', // 业务类型
        fundCode: '', // 产品序号
        fundAccountCode: '', // 组合编码
        operatorName: getUser().userName,
        orderUser: getUser().userCode,
        orderPurpose: '1', // 指令用途
        investType: '1', // 投资类型
        marketCode: '', // 市场序号
        reportCode: '', // 申报代码
        orderDirection: '', // 订单方向
        orderPriceType: '1', // 价格模式
        orderPrice: '', // 指令价格
        orderAmount: '', // 指令数量
        orderBalance: '', // 指令金额
        orderLevel: '1', // 指令优先级
        // cancelType: '3',
        clearSpeed: '1', // 清算速度
        opponentCode: '', // 交易对手编码
        instructionType: '13',
        yield: '',
    };

    fundCodeSelectData: any[] = []; // 产品序号下拉框数据
    fundAccountCodeSelectData: any[] = []; // 组合编码下拉框数据
    opponentCodeSelectData: any[] = []; // 交易对手方下拉数据
    stockCodeSelectData: any[] = []; // 证券代码下拉框数据
    orderDirectionSelectData: any[] = []; // 订单方向下拉框数据
    innerOrderDirectionData: any[] = [];

    totalInterest: string = '';
    fullBalance: string = '';
    fullPrice: string = '';
    selectLoading: boolean = false; // 下拉框远程搜索时的加载状态
    stockInfo: any = {};

    async mounted() {
        // 获取交易对手方
        this.getOpponentCode('');
        // 获取证券代码下拉框数据
        this.getstockCodeList('');
        // 获取产品信息 (产品序号下拉框数据)
        this.fundCodeSelectData = await SGU_CACHE('FundInfo', '/fundInfo/list', []);
        // 获取组合编码下拉框数据
        let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
        arr.forEach(item => {
            this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
        });
    }

    @Watch('detail', { immediate: true, deep: true })
    async onWatchDetail() {
        if (this.detail && Object.keys(this.detail).length) {
            let instruction: any = {};
            for (const key in this.detail) {
                instruction[key] = this.detail[key];
            }
            this.instruction = JSON.parse(JSON.stringify(instruction));
            this.instruction.businClass = this.instruction.businessType;
            this.fullPrice = instruction.fullPrice;
            this.totalInterest = instruction.totalInterest;
            this.fullBalance = instruction.fullBalance;
            console.log(this.instruction, 'this.instruction');
        }
    }

    @Watch('selectStockInfo', { immediate: true, deep: true })
    onWatchStockInfo() {
        if (this.selectStockInfo) {
            // this.stockInfo = this.selectStockInfo;
            this.instruction.stockCode = this.selectStockInfo?.stockCode;
            this.instruction.reportCode = this.selectStockInfo?.reportCode;
            this.instruction.marketCode = this.selectStockInfo?.marketCode;
            if (this.selectStockInfo.marketCode && this.selectStockInfo.stockType) {
                this.handleStockBusinessType(this.selectStockInfo.marketCode, this.selectStockInfo.stockType, true);
            }
        }
    }

    /**
     * 判断字段颜色
     */
    @Watch('instruction', { immediate: true, deep: true })
    handleFieldColor() {
        if (this.instruction.orderDirection === '3') {
            this.textColor = highlightColor()[1];
        } else if (this.instruction.orderDirection === '4') {
            this.textColor = highlightColor()[2];
        } else {
            this.textColor = highlightColor()[0];
        }
    }

    /* ******************** 指令表单相关start ********************** */

    getInputNumber(args: any) {
        let value = args[0];
        let field = args[1];
        if (['orderAmount', 'orderPrice', 'orderBalance', 'yield'].includes(field)) {
            this.instruction[field] = value;
        }
        if (field === 'orderAmount') {
            this.handleOrderAmount();
            this.totalInterest = this.calcInterest(this.instruction.orderAmount, this.stockInfo.tDayInterest).toString();
        } else if (field === 'orderPrice') {
            this.handleOrderPrice();
        } else if (field === 'fullPrice') {
            this.fullPrice = value;
            this.handleFullPrice();
        }
        this.$emit('handleSettingValue', this.instruction, '');
    }

    // 参数变动
    handleChange(value, field) {
        if (field === 'fundCode') {
            this.handleFundCodeChange(value);
        } else if (field === 'stockCode') {
            this.handleStockCode(value, true);
        } else if (field === 'opponentCode') {
            this.getOpponentCode(value);
        }
        this.$emit('handleSettingValue', this.instruction, '');
    }

    /**
     *  处理订单数量变动
     */
    handleOrderAmount() {
        if (this.instruction.orderPrice) {
            this.calcForm('orderPrice');
        } else if (this.fullPrice) {
            this.calcForm('fullPrice');
        }
        // 如果数量为0，净价金额、净价金额、应计利息 为空
        if (!this.instruction.orderAmount) {
            this.fullBalance = '';
            this.instruction.orderBalance = '';
            this.totalInterest = '';
            // return;
        }
    }

    /**
     *  处理净价价格变动 ，
     */
    handleOrderPrice() {
        if (this.instruction.orderPrice) {
            // 净价价格不为空，用数量和净价价格计算
            if (this.instruction.orderAmount) {
                this.calcForm('orderPrice');
            } else {
                // 指令数量为空时，只计算全价价格
                this.fullPrice = this.calcFullPrice(this.instruction.orderPrice, this.stockInfo.tDayInterest);
            }
        } else {
            this.fullBalance = '';
            this.instruction.orderBalance = '';
            this.fullPrice = '';
            // this.totalInterest = '';
        }
    }

    /**
     *  处理全价价格变动
     */
    handleFullPrice() {
        if (this.fullPrice) {
            if (this.instruction.orderAmount) {
                this.calcForm('fullPrice');
            } else {
                // 指令数量为空时，只计算净价价格
                this.instruction.orderPrice = this.calOrderPrice(this.fullPrice, this.stockInfo).toFixed(2);
            }
        } else {
            this.fullBalance = '';
            this.instruction.orderPrice = '';
            this.instruction.orderBalance = '';
            // this.totalInterest = '';
        }
    }

    calcForm(calcType) {
        // 拿净价价格计算
        if (calcType === 'orderPrice' && this.instruction.orderPrice) {
            // 净价金额
            this.instruction.orderBalance = (Number(this.instruction.orderPrice) * Number(this.instruction.orderAmount)).toFixed(2).toString();
            // 应计利息
            let interest = this.calcInterest(this.instruction.orderAmount, this.stockInfo.tDayInterest);
            // 全价价格
            this.fullPrice = this.calcFullPrice(this.instruction.orderPrice, this.stockInfo.tDayInterest);
            // 总应计利息
            this.totalInterest = interest.toString();
            // 全价金额
            this.fullBalance = (Number(this.instruction.orderBalance) + Number(this.totalInterest)).toFixed(2);
        } else if (calcType === 'fullPrice' && this.fullPrice) {
            // 净价价格为空，全价价格有值,拿全价价格计算净价价格
            this.instruction.orderPrice = this.calOrderPrice(this.fullPrice, this.stockInfo).toFixed(2);
            // 净价金额
            this.instruction.orderBalance = (Number(this.instruction.orderPrice) * Number(this.instruction.orderAmount)).toFixed(2).toString();
            // 应计利息
            let interest = this.calcInterest(this.instruction.orderAmount, this.stockInfo.tDayInterest);
            // 总应计利息
            this.totalInterest = interest.toString();
            // 全价金额
            this.fullBalance = (Number(this.instruction.orderBalance) + Number(this.totalInterest)).toFixed(2);
        }
    }

    // 组合编码下拉框计算属性
    get computedFundAccountCodeSelectData() {
        return this.fundAccountCodeSelectData[this.instruction.fundCode] || [];
    }

    // 指令金额 大写中文
    get computedorderBalanceChinese() {
        return NumberToWords(this.instruction.orderBalance.toString());
    }

    /**
     * 应计利息 = 指令数量 *T日百元利息
     */
    calcInterest(orderAmount, tDayInterest) {
        let result = Number(orderAmount) * Number(tDayInterest || 0);
        return result;
    }

    /**
     * 全价价格计算公式 全价价格=净价价格+T日百元利息(最新计算逻辑)
     */
    calcFullPrice(orderPrice, interest) {
        let result = String((Number(orderPrice || 0) + Number(interest || 0)).toFixed(2));
        if (result === 'NaN' || result === 'Infinity') {
            return '0';
        } else {
            return result;
        }
    }

    /**
     *  反推
     * 净价价格 = 全价价格- T日百元利息(新)
     */
    calOrderPrice(fullPrice, stockInfo) {
        return fullPrice - (stockInfo.tDayInterest || 0);
    }

    getEntryslist(val: any) {
        this.instruction.fundCode = val;
        this.handleFundCodeChange(val);
    }

    // 获取证券代码下拉框数据
    getstockCodeList(e: string) {
        this.selectLoading = true;
        this.$axios
            .post('/dict/stock/select/' + 2, {
                dictKey: e,
                dictKeyName: e,
            })
            .then((res: any) => {
                this.stockCodeSelectData = res || [];

                this.selectLoading = false;
            });
    }

    // 获取交易对手方数据
    getOpponentCode(value: string) {
        this.$axios
            .post('/dict/opponent/select', {
                dictKey: value,
                dictKeyName: value,
            })
            .then((res: any) => {
                this.opponentCodeSelectData = res;
            });
    }

    handleOpponentVisibleChange(val: any) {
        if (!val) {
            this.getOpponentCode('');
        }
    }

    handleStockClear() {
        this.orderDirectionSelectData = [];
        this.getstockCodeList('');
    }

    handleStockVisibleChange(val) {
        if (!val) {
            this.getstockCodeList('');
        }
    }

    handleFundCodeChange(value: string) {
        let fund = this.fundCodeSelectData.find(item => item.fundCode === value) || {};
        let fundAccount = (this.fundAccountCodeSelectData[this.instruction.fundCode] || [])[0] || {};
        this.instruction.fundNameSt = fund.fundNameSt;
        this.instruction.fundAccountCode = fundAccount.fundAccountCode;
        this.instruction.fundAccountName = fundAccount.fundAccountName;
    }

    // 证券代码选中事件 => 请求 证券信息 & 订单方向
    handleStockCode(value: string, reset: boolean) {
        if (reset) {
            this.instruction.orderDirection = '';
            // this.instruction.orderAmount = '';
            this.instruction.orderBalance = '';
            this.instruction.orderPrice = '';
            this.fullPrice = '';
            this.fullBalance = '';
            this.totalInterest = '';
        }
        if (value) {
            this.$axios('/baseInfomation/stockCode/' + value).then((res: any) => {
                if (res) {
                    if (res.foreverStock) {
                        this.instruction.investType = '3';
                    } else {
                        this.instruction.investType = '1';
                    }
                }
            });
            this.stockInfo = this.stockCodeSelectData.find(item => item.stockCode === value);
            this.$emit('getStockInfo', this.stockInfo);
            if (this.stockInfo.marketCode && this.stockInfo.stockType) {
                this.handleStockBusinessType(this.stockInfo.marketCode, this.stockInfo.stockType, reset);
            }
            let stockType = null;
            for (let i = 0; i < this.stockCodeSelectData.length; i++) {
                const ele = this.stockCodeSelectData[i];
                if (ele.stockCode === value) {
                    stockType = ele.stockType;
                    this.instruction.marketCode = ele.marketCode;
                    this.instruction.reportCode = ele.reportCode;
                    break;
                }
            }
        } else {
            this.orderDirectionSelectData = [];
        }
    }

    // 根据证券信息获取业务类型
    async handleStockBusinessType(marketCode, stockType, type) {
        this.orderDirectionSelectData = [];
        let res = await getBusinessType(marketCode, stockType);
        if (res && res.length > 0) {
            this.innerOrderDirectionData = res;
            this.innerOrderDirectionData.filter(ele => {
                if (ele.dictKey == this.instruction.businClass) {
                    this.orderDirectionSelectData = JSON.parse(ele['innerDictionary'] || {});
                    if (this.orderDirectionSelectData.length && type) {
                        this.instruction.orderDirection = this.orderDirectionSelectData[0].dictKey;
                    }
                }
            });
        }
    }

    /* ******************** 指令表单相关end ********************** */
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-time/styles/order-form';
</style>
